package com.huibei.wateradmin.authority.service;

import com.huibei.wateradmin.authority.domain.Menu;
import com.huibei.wateradmin.authority.domain.User;
import com.huibei.wateradmin.authority.message.ClientMenuInfo;
import com.huibei.wateradmin.authority.repository.MenuRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by wanglinlin on 2016/7/20.
 */
@Service
@Transactional
public class MenuService {
    @Autowired
    private MenuRepository menuRepository;
    @Autowired
    private UserService userService;

    public Page<Menu> findAll(PageRequest request) {
        return menuRepository.findAll(request);
    }

    public ClientMenuInfo findById(Long id) {
        Menu menu = menuRepository.findOne(id);
        if (menu == null) {
            return new ClientMenuInfo();
        }
        ClientMenuInfo clientMenuInfo = new ClientMenuInfo(menu);
        return clientMenuInfo;
    }

    public void updateMenu(Long menuId, String name, String url, String icon, Long parentId) {

        Menu menu = new Menu(menuId, name, url, icon);
        menu = menuRepository.saveAndFlush(menu);
        Menu pmenu = new Menu(parentId);
        if (parentId == null) {
            pmenu = null;
        }
        menu.setParentMenu(pmenu);

    }

    public List<ClientMenuInfo> getUserMenus(Long userId) {
        User user = userService.findById(userId);
        List<Menu> userMenuList = user.getRole().getMenus();
        List<Menu> menus = menuRepository.findByParentMenuIsNull();//查询所有菜单
        menus = menus.stream().filter(menu -> userMenuList.contains(menu)).collect(Collectors.toList());//过滤出当前用户菜单
        System.out.println(">>menus.size>>"+menus.size());
        List<ClientMenuInfo> clientMenuInfos = new ArrayList<>();
        for (Menu menu : menus) {  //这里可以转化成java8的方式
            clientMenuInfos.add(ClientMenuInfo.convertToClientMenu(menu,userMenuList));
        }
        System.out.println(">>>>>>>>>>>>");
        return clientMenuInfos;
    }

    public Menu findByURL(String servletPath) {
        List<Menu> menus = menuRepository.findByUrl(servletPath);
        if (menus.size() > 0) {
            return menus.get(0);
        } else {
            return null;
        }
    }
}
